package com.phoenix.blacklistmanager;

import java.lang.reflect.Method;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;

public class BlackListReceiver  extends BroadcastReceiver {

	private ITelephony telephonyService;
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		
		telephonyService = telephoneService(context);

		Bundle extras = intent.getExtras();
	    if (extras != null) {
	      String state = extras.getString(TelephonyManager.EXTRA_STATE);
	      Log.w("DEBUG","phone state: "+ state);
	      if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
	        String phoneNumber = extras
	            .getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
	        Log.w("DEBUG", "phone number: "+phoneNumber);
	        
	        if (phoneNumber.equals("0908828061")) {
	        	Log.i("telephone services", "End call by telephone");
					try {
						telephonyService.endCall();
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
	      }
	    }
	}
	private ITelephony telephoneService(Context context)
	{
		TelephonyManager tm = (TelephonyManager) context
        .getSystemService(Context.TELEPHONY_SERVICE);
			 try {
			     // Java reflection to gain access to TelephonyManager's
			     Log.v("debug", "Get getTeleService...");
			     Class c = Class.forName(tm.getClass().getName());
			     Method m = c.getDeclaredMethod("getITelephony");
			     m.setAccessible(true);
			     ITelephony telephonyService = (ITelephony) m.invoke(tm);
			 } catch (Exception e) {
			     e.printStackTrace();
			     Log.e("debug",
			             "FATAL ERROR: could not connect to telephony subsystem");
			     Log.e("debug", "Exception object: " + e);
			 }
			 return telephonyService;
		
	}
}
